package com.javasm.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//@Component
public class JWTUtil {

    private static final String uidkey="uid";

    //登录token的密钥
    private static final String LOGIN_TOKEN_KEY = "FzoCKjJctKVflDZ0zMUn49WRNuvE4TCfaAWTclwkNw4=";

    //重置密码token的密钥
    private static final String RESET_TOKEN_KEY = "IN6fDjbcp45OpD/ePmUiMffJKYCXHzNOfwUsE7a1PTc=";

    private static final Integer TokenExpMills= 30; // 失效时间30分钟

//    private static SsmInfo info;
//    @Resource
//    public void setSsmInfo(SsmInfo ssmInfo) {
//       info = ssmInfo;
//    }

    public static void generateKey() {
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String secretString = Encoders.BASE64.encode(key.getEncoded());
        System.out.println(secretString);
    }

    public static String generateLoginToken(String uid) {
        Map<String, String> map = new HashMap<>();
        map.put(uidkey, uid);
        Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(LOGIN_TOKEN_KEY));
        Date current = new Date();
        Date expDate = new Date(current.getTime() + TokenExpMills * 60 * 1000);
        String jws = Jwts.builder()
                .setClaims(map)
                .setIssuedAt(current)
                .setExpiration(expDate)
                .signWith(key)
                .compact();
        return jws;
    }

    public static Claims parseLoginToken(String jwt) {
        Jws<Claims> jws;
        try {
            jws = Jwts.parserBuilder()
                    .setSigningKey(LOGIN_TOKEN_KEY)
                    .build()
                    .parseClaimsJws(jwt);
            Claims body = jws.getBody();
            return body;
        } catch (Exception ex) {
            return null;
        }
    }

    public static String getUid(Claims c){
        Object o = c.get(uidkey);
        return (String)o;
    }
    public static String generateToken(String uid,String keystr) {//加密
        Map<String, String> map = new HashMap<>();
        map.put(uidkey, uid);
        Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(keystr));
        Date current = new Date();
        Date expDate = new Date(current.getTime() + TokenExpMills * 60 * 1000);
        String jws = Jwts.builder()
                .setClaims(map)
                .setIssuedAt(current)
                .setExpiration(expDate)
                .signWith(key)
                .compact();
        return jws;
    }
    public static String parseToken(String jwt,String keystr) {//解密
        Jws<Claims> jws;
        try {
            jws = Jwts.parserBuilder()
                    .setSigningKey(keystr)
                    .build()
                    .parseClaimsJws(jwt);
            Claims body = jws.getBody();
            return JWTUtil.getUid(body);
        }catch (SignatureException e){
            //token签名错误
            return e.getMessage();
        }catch(ExpiredJwtException e){
            //超时
            return e.getMessage();
        }catch (Exception e){
            return null;
        }
    }
    public static void main(String[] args) {
        String s = generateLoginToken("15516197241");
        System.out.println(s);
        String t= "eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxNTUxNjE5NzI0MSIsImlhdCI6MTczNjIwNjkxNSwiZXhwIjoxNzM2MjA4NzE1fQ.P41Nubd46QKpsnsODIydHng3BOg80r_IXB9b2f-ICf0";
        Claims claims = parseLoginToken(t);//再次按照密钥对body进行加密生成文本，比较通过
        System.out.println(claims.getIssuedAt());
        System.out.println(claims.getExpiration());
        System.out.println(claims.get("uid"));

        //eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxNTUxNjE5NzI0MSIsImlhdCI6MTY1NTQ1MTc5NiwiZXhwIjoxNjU1NDUzNTk2fQ.cz2ew2EytbB0rVZNd5po39cKh2pa-FpBsy8JTLCbx_4
        //eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxNTUxNjE5NzI0MSIsImlhdCI6MTY1NTQ1MTcxNiwiZXhwIjoxNjU1NDUzNTE2fQ.LLRh2Idc4j_tIVJ-hBp7W0PJAJ7BLATYs7RXw-QD0v0
    }
}
